home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13148 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  61 lines

  1. Path: sun001.spd.dsccc.com!jmccarty
  2. From: jmccarty@sun1307.spd.dsccc.com (Mike McCarty)
  3. Newsgroups: comp.lang.c,comp.unix.programmer
  4. Subject: Re: Q: '\n' character - strtok trick
  5. Date: 4 Apr 1996 22:49:49 GMT
  6. Organization: DSC Communications Corporation
  7. Message-ID: <4k1jmd$ifr@sun001.spd.dsccc.com>
  8. References: <31616F63.481D@lava.weeg.uiowa.edu> <828493319snz@genesis.demon.co.uk> <828542474.7672@tertio.demon.co.uk> <4ju9m0$nq9@belle.bork.com>
  9. NNTP-Posting-Host: sun1307.spd.dsccc.com
  10.  
  11. In article <4ju9m0$nq9@belle.bork.com>, BOFH <root@belle.bork.com> wrote:
  12. )alord@tertio.co.uk wrote:
  13. ): Although the behaviour of strtok() is well defined I try to avoid it like the
  14. ): plague because it uses a static area to maintain state. If another function
  15. ): happens to call it between successive invocations then your screwd.
  16. )
  17. )Well, yes it does use a static data area to store it's state, but that
  18. )doesn't matter.  When you call the function this way, strtok will return
  19. )a pointer to the beginning of the string that it chopped a newline off
  20. )of, AND will insert a NULL character into the location of the newline.
  21. )After it returns, you are done.  Your string has had the newline taken
  22. )off, and you are done with strtok.  strtok will internally remember where
  23. )it last took a delimiter off, but it only needs it when strtok is called
  24. )with a NULL buffer anyway.
  25. )
  26. )The only problem with this is that you could be in the middle of parsing
  27. )a string with strtok, and then you attempted to strtok(buffer,...), which
  28. )would definately cause a problem.
  29. )
  30. )My $0.02.
  31. )
  32. )
  33. )Randy Scott <scottr@belle.bork.com>
  34.  
  35.  
  36. I usually do this (from memory only, so argument order etc. may be off):
  37.  
  38.     boolean    readline(char *buffer,size_t max_size,FILE *stream) {
  39.         boolean    result;
  40.         size_t    place;
  41.  
  42.         if (fgets(buffer,max_size,stream) == NULL)
  43.             result = false;
  44.         else {
  45.             place = strlen(buffer)-1;
  46.             if (place >= 0 && buffer[place] == '\n')
  47.                 buffer[place] = '\0';
  48.             result = true;
  49.         }
  50.         return result;
  51.     }
  52.  
  53. And then exclusively call readline(.,.,.) in my program.
  54.  
  55. Mike
  56. -- 
  57. ----
  58. char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}
  59.  
  60. I don't speak for DSC.         <- They make me say that.
  61.